import os
import random
from collections import Counter
from django.core.management.base import BaseCommand
from core.models import Document, Tag, Category
from django.utils.text import slugify
import re

class Command(BaseCommand):
    help = '从文档标题和目录中提取主流技术栈标签'

    def get_random_color(self, tech_name='default'):
        """根据技术栈获取对应的颜色"""
        colors = {
            # 后端语言 - 蓝色系
            'Python': '#1890ff',
            'Java': '#40a9ff',
            'Go': '#69c0ff',
            
            # Web框架 - 绿色系
            'Django': '#52c41a',
            'Flask': '#73d13d',
            'Spring': '#95de64',
            'FastAPI': '#b7eb8f',
            
            # 数据库 - 橙色系
            'MySQL': '#fa8c16',
            'PostgreSQL': '#ffa940',
            'MongoDB': '#ffc069',
            'Redis': '#ffd591',
            
            # 运维工具 - 紫色系
            'Docker': '#722ed1',
            'Kubernetes': '#9254de',
            'Linux': '#b37feb',
            'Nginx': '#d3adf7',
            
            # 消息队列 - 青色系
            'RabbitMQ': '#13c2c2',
            'Kafka': '#36cfc9',
            
            # 监控工具 - 红色系
            'Prometheus': '#f5222d',
            'Grafana': '#ff4d4f',
            
            # 默认颜色
            'default': '#40a9ff',
        }
        return colors.get(tech_name, colors['default'])

    def extract_tech_words(self, text):
        """提取技术相关词汇"""
        # 定义主流技术栈及其对应的标准名称
        tech_patterns = {
            # 后端语言
            r'python|py\b': 'Python',
            r'java\b|jdk|jvm': 'Java',
            r'golang|go\b': 'Go',
            
            # Web框架
            r'django': 'Django',
            r'flask': 'Flask',
            r'fastapi': 'FastAPI',
            r'spring|springboot|spring boot': 'Spring',
            
            # 数据库
            r'mysql': 'MySQL',
            r'postgresql|postgres': 'PostgreSQL',
            r'mongodb': 'MongoDB',
            r'redis': 'Redis',
            
            # 运维工具
            r'docker': 'Docker',
            r'kubernetes|k8s': 'Kubernetes',
            r'linux': 'Linux',
            r'nginx': 'Nginx',
            
            # 消息队列
            r'rabbitmq': 'RabbitMQ',
            r'kafka': 'Kafka',
            
            # 监控工具
            r'prometheus': 'Prometheus',
            r'grafana': 'Grafana',
        }
        
        found_techs = set()
        text_lower = text.lower()
        
        for pattern, tech_name in tech_patterns.items():
            if re.search(pattern, text_lower):
                found_techs.add(tech_name)
        
        return found_techs

    def handle(self, *args, **options):
        self.stdout.write('开始清理旧标签...')
        # 清理所有已存在的标签
        Tag.objects.all().delete()
        self.stdout.write(self.style.SUCCESS('旧标签清理完成！'))
        
        self.stdout.write('开始提取主流技术栈标签...')
        
        # 获取所有文档
        documents = Document.objects.all()
        
        # 用于存储所有技术标签
        all_techs = set()
        
        # 存储文档与技术的映射关系
        doc_techs = {}
        
        # 定义技术栈的顺序
        tech_order = {
            # 后端语言
            'Python': 10,
            'Java': 11,
            'Go': 12,
            
            # Web框架
            'Django': 20,
            'Flask': 21,
            'FastAPI': 22,
            'Spring': 23,
            
            # 数据库
            'MySQL': 30,
            'PostgreSQL': 31,
            'MongoDB': 32,
            'Redis': 33,
            
            # 运维工具
            'Docker': 40,
            'Kubernetes': 41,
            'Linux': 42,
            'Nginx': 43,
            
            # 消息队列
            'RabbitMQ': 50,
            'Kafka': 51,
            
            # 监控工具
            'Prometheus': 60,
            'Grafana': 61,
        }
        
        for doc in documents:
            doc_techs[doc] = set()
            
            # 从文档标题中提取
            if doc.title:
                techs = self.extract_tech_words(doc.title)
                doc_techs[doc].update(techs)
                all_techs.update(techs)
            
            # 从文档所属目录中提取
            if doc.category:
                techs = self.extract_tech_words(doc.category.title)
                doc_techs[doc].update(techs)
                all_techs.update(techs)
        
        # 创建技术标签
        for tech_name in sorted(all_techs):
            slug = slugify(tech_name)
            if not slug:
                slug = tech_name.lower()
            
            tag = Tag.objects.create(
                name=tech_name,
                slug=slug,
                description=f'与{tech_name}技术相关的文档',
                type='tech',
                color=self.get_random_color(tech_name),
                icon='code',  # 使用代码图标
                order_index=tech_order.get(tech_name, 100)  # 使用预定义的顺序，默认值为100
            )
            
            self.stdout.write(self.style.SUCCESS(f'创建新技术标签: {tech_name}'))
            
            # 将标签关联到相关文档
            for doc, techs in doc_techs.items():
                if tech_name in techs:
                    doc.tags.add(tag)
                    self.stdout.write(f'将技术标签 {tech_name} 添加到文档: {doc.title}')
        
        self.stdout.write(self.style.SUCCESS('标签提取和导入完成！')) 